﻿using System.IO;
using JetBlack.IO;

namespace JetBlack.FeedBus.Messages
{
    internal abstract class Message
    {
        public readonly MessageType MessageType;

        public Message(MessageType messageType)
        {
            MessageType = messageType;
        }

        public static Message Read(Stream reader)
        {
            MessageType messageType = (MessageType)reader.ReadByte();

            switch (messageType)
            {
                case MessageType.SubscriberMessage:
                    return SubscriberMessage.Read(reader);
                case MessageType.ClientMessage:
                    return ClientMessage.Read(reader);
                case MessageType.ForwardedSubscriptionRequest:
                    return ForwardedSubscriptionRequest.Read(reader);
                case MessageType.NotificationRequest:
                    return NotificationRequest.Read(reader);
                case MessageType.SubscriptionRequest:
                    return SubscriptionRequest.Read(reader);
                default:
                    throw new InvalidDataException("unknown message type");
            }
        }

        public virtual Stream Write(Stream writer)
        {
            writer.Write((byte)MessageType);
            return writer;
        }
    }
}
